<template>
  <view class="form-container">
    <!-- 住院号输入框 -->
    <FormInput label="住院号" v-model="form.hospitalNumber" placeholder="请输入住院号" type="number" :required="true" />
    <!-- 新密码输入框 -->
    <FormInput label="新密码" v-model="form.newPassword" placeholder="请输入新密码" type="password" :required="true" />
    <!-- 确认密码输入框 -->
    <FormInput label="确认密码" v-model="form.confirmPassword" placeholder="请再次输入密码" type="password" :required="true" />
    <!-- 验证码输入框 -->
    <FormInput label="身份证号" v-model="form.idNumber" placeholder="请输入身份证号" type="number" :required="true" />
    <!-- 提交按钮 -->
    <button class="button" @click="resetKey">提交</button>
  </view>
</template>

<script>
import FormInput from '../../components/FormInput.vue';
import FormInputWithButton from '../../components/FormInputWithButton.vue';
import config from '../../config.js';

export default {
  components: {
    FormInput,
    FormInputWithButton
  },
  data() {
    return {
      form: {
        hospitalNumber: '',
        newPassword: '',
        confirmPassword: '',
        idNumber: ''
      },
      countdown: 0
    };
  },
  methods: {
	  validateIdCard(idNumber) {
	    // 空值检查
	    if (!idNumber) {
	      uni.showToast({
	        title: '请输入身份证号',
	        icon: 'none'
	      });
	      return false;
	    }
	  
	    // 基本格式校验（18位）
	    if (!/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/.test(idNumber)) {
	      uni.showToast({
	        title: '请输入18位有效身份证号',
	        icon: 'none'
	      });
	      return false;
	    }
	  
	    // 校验码计算（GB 11643-1999标准）
	    const weight = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; // 加权因子
	    const checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']; // 校验码对照
	    
	    let sum = 0;
	    for (let i = 0; i < 17; i++) {
	      sum += parseInt(idNumber[i]) * weight[i];
	    }
	  
	    // 校验码比对
	    const lastChar = idNumber[17].toUpperCase();
	    if (checkCodes[sum % 11] !== lastChar) {
	      uni.showToast({
	        title: '身份证校验码错误',
	        icon: 'none'
	      });
	      return false;
	    }
	  
	    return true; // 验证通过
	  },
    async resetKey() {
      // 表单验证
      if (!this.form.hospitalNumber || !this.form.newPassword || !this.form.confirmPassword || !this.form.idNumber) {
        uni.showToast({
          title: '请填写完所有信息',
          icon: 'none'
        });
        return;
      }
      
      // 验证住院号是否纯数字组成
      if (!/^\d+$/.test(this.form.hospitalNumber)) {
        uni.showToast({
          title: '请输入正确的住院号',
          icon: 'none'
        });
        return;
      }
	  
	  if(!this.validateIdCard(this.form.idNumber)) {
		  uni.showToast({
		    title: '请输入正确的身份证号',
		    icon: 'none'
		  });
		  return;
	  }
      
      // 验证密码长度至少6位
      if (this.form.newPassword.length < 6) {
        uni.showToast({
          title: '密码长度至少6位',
          icon: 'none'
        });
        return;
      }
      
      // 验证两次密码输入是否一致
      if (this.form.newPassword !== this.form.confirmPassword) {
        uni.showToast({
          title: '两次密码不一致',
          icon: 'none'
        });
        return;
      }
      
      try {
        const submitData = {
          hospitalNumber: this.form.hospitalNumber,
          password: this.form.newPassword,
          idNumber: this.form.idNumber
        };
        const response = await uni.request({
          url:  `${config.baseUrl}/patient/resetKey`,
          method: 'POST',
          data: submitData,
          header: {
            'content-type': 'application/json'
          }
        });
        if (response.statusCode === 200 && response.data && response.data.code === 1) {
          uni.navigateTo({
            url: '/pages/login/login'
          });
		  uni.showToast({
		    title: '重置密码成功',
		    icon: 'success'
		  });
        } else {
          throw new Error(response.data?.msg || '重置密码失败');
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '重置密码失败，请重试',
          icon: 'none'
        });
      }
    }
  }
};
</script>

<style lang="scss">
.form-container {
  background-color: #f8f9fa;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 20rpx;
}

.button {
  border-radius: 8px;
  background-color: #4361ee;
  color: white;
  width: 400rpx;
  margin: 0 auto;
  margin-top: 50rpx;
}


</style> 